#include "stdafx.h"
#include "MyControls/SequenceView.h"
#include "MyControls/Sequence.h"
#include <MyControls/Resource.h>

namespace My {

SequenceView::SequenceView()
{
	m_nTimer = 0;
	m_MinScale = 0.01f;
	m_MaxScale = 100;
	ReadSettings();
}

SequenceView::~SequenceView()
{
	WriteSettings();
}

bool SequenceView::IsEmpty() const 
{ 
	return GetSequence() == 0 || GetSequence()->IsEmpty(); 
}

void SequenceView::SetFramerate(float fps) 
{ 
	if (fps < 0.01)
		fps = 0.01;
	else if (fps > 100)
		fps = 100;
	if (m_PlayFramerate != fps) {
		m_PlayFramerate = fps; 
		if (IsPlaying()) {
			StopTimer();
			StartTimer();
		}
		DispatchEvent(FramerateChange(* this));
	}
}

BEGIN_MESSAGE_MAP(SequenceView, ZoomBench)
	ON_PLAYER_COMMANDS()
	ON_WM_TIMER()
END_MESSAGE_MAP()

// SequenceView message handlers

void SequenceView::ProcessEvent(My::Event & e)
{
	if (e.Is<Sequence::PreviewFrameChange>()) {
		InvalidateBuffer();
		return;
	}
	if (e.Is<Sequence::OpenEvent>()) {
		ResizeBench(GetSequence()->GetDim());
		InvalidateBuffer();
		return;
	}
	if (e.Is<Sequence::CloseEvent>()) {
		SetPlayMode(PlayStop);
		ResizeBench(0, 0);
		SetActiveTool(0);
		EraseBuffer();
		return;
	}
}

BOOL SequenceView::PreCreateWindow(CREATESTRUCT& cs) 
{
	if (!CWnd::PreCreateWindow(cs))
		return FALSE;

	//cs.dwExStyle |= WS_EX_CLIENTEDGE;
	cs.style &= ~WS_BORDER;
	cs.lpszClass = AfxRegisterWndClass(CS_HREDRAW|CS_VREDRAW|CS_DBLCLKS, 
		::LoadCursor(NULL, IDC_ARROW), reinterpret_cast<HBRUSH>(COLOR_WINDOW+1), NULL);

	return TRUE;
}

void SequenceView::StartTimer()
{
	if (m_nTimer == 0)
		m_nTimer = SetTimer(1, GetPlayTimerDelay(), 0);
}

void SequenceView::StopTimer()
{
	if (m_nTimer != 0) {
		KillTimer(m_nTimer);
		m_nTimer = 0;
	}
}

void SequenceView::WriteSettings()
{
	AfxGetApp()->WriteProfileInt("Time", "PlayFramerate", m_PlayFramerate * 1000);
	AfxGetApp()->WriteProfileInt("Time", "Loop", GetLoop() ? 1 : 0);
}

void SequenceView::ReadSettings()
{
	m_PlayFramerate = AfxGetApp()->GetProfileInt("Time", "PlayFramerate", 10000) * 0.001f;
	SetLoop(AfxGetApp()->GetProfileInt("Time", "Loop", 1) != 0);
}

void SequenceView::PaintRect(CDC * pDC, const CRect & r)
{
	if (GetSequence()->IsEmpty())
		return;

	CRect rClient = r, rImage;

	BestWholeMapping(rClient, rImage);

	size_extent dim = GetSequence()->GetDim();
	const CRect rClip(0, 0, dim.sx, dim.sy);
	CRect rIntersection;
	if (!rIntersection.IntersectRect(rImage, rClip))
		return;

	if (rIntersection != rImage)
		rClient = BenchToClient(rImage = rIntersection);

	//draw image itself
	int nStretchMode = GetScale() > 1 ? COLORONCOLOR : HALFTONE;
	VERIFY(pDC->SetStretchBltMode(nStretchMode));	
	SetBrushOrgEx(pDC->m_hDC, 0, 0, 0);

	PaintImageRect(pDC, rClient, rImage);
}

void SequenceView::OnTimer(UINT nIDEvent)
{
	TimeStep();
	ZoomBench::OnTimer(nIDEvent);
}

} //namespace My
